package com.zf.yichat.controller.sys;



import com.google.common.collect.Lists;
import com.zf.yichat.config.utils.MenuUtils;
import com.zf.yichat.controller.BaseController;
import com.zf.yichat.model.SysMenu;
import com.zf.yichat.model.SysUserRole;
import com.zf.yichat.service.SysMenuService;
import com.zf.yichat.service.SysRoleService;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 189
 * @date 20230506
 */
@Controller
@RequestMapping("role")
public class RoleController extends BaseController {

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService menuService;

    /**
     * 控制页面访问
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "sys/role/index";
    }

    /**
     * 查询角色列表
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public FsResponse list(Integer page, Integer limit, String name) {
        return roleService.selectIndexList(FsPage.init(page, limit), name);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping("save/index")
    public String saveIndex(Integer id) {
        SysUserRole role = roleService.selectById(id);
        getRequest().setAttribute("role", Objects.nonNull(id) ? roleService.selectById(id) : null);
        List<SysMenu> menuList = Objects.nonNull(role) ? menuService.selectListByRoleId(id) : Lists.newArrayList();
        getRequest().setAttribute("menuList", MenuUtils.generateMenuDataChoose(menuService.selectAll(),menuList.stream().map(SysMenu::getId).collect(Collectors.toList())));
        return "sys/role/save";
    }

    /**
     * 添加角色
     * @param role
     * @param menus
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public FsResponse save(SysUserRole role, String menus) {
        return FsResponseGen.gen(roleService.save(role, menus) == 1);
    }


}
